package com.yboot.starter.holiday.core.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.yboot.starter.caffeine.core.LocalCache;
import com.yboot.starter.holiday.core.HolidayDataStorageService;
import com.yboot.starter.holiday.core.HolidayManage;
import com.yboot.starter.holiday.core.HolidaySynchronizerService;
import com.yboot.starter.holiday.core.vo.HolidayResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 *
 * @author yangcs
 * @date 2025/8/11
 */
@Slf4j
public class DefaultHolidayManageImpl implements HolidayManage {

    private HolidaySynchronizerService holidaySynchronizerService;
    private HolidayDataStorageService holidayDataStorageService;

    public DefaultHolidayManageImpl(HolidaySynchronizerService holidaySynchronizerService, HolidayDataStorageService holidayDataStorageService) {
        this.holidaySynchronizerService = holidaySynchronizerService;
        this.holidayDataStorageService = holidayDataStorageService;
    }

    @Override
    public List<HolidayResponseVo> getHoliday(String year) {
        List<HolidayResponseVo> list = holidayDataStorageService.get(year);
        if (CollectionUtils.isEmpty(list)) {
            try {
                list = holidaySynchronizerService.syncHoliday(year);
                holidayDataStorageService.save(year, list);
            } catch (Exception e) {
                log.error("在线同步节假日失败");
                list = new ArrayList<>();
            }
        }
        return list;
    }

    @Override
    public boolean isHoliday(String date) {
        // 是否为周末（周六或周日）
        boolean isWeekend = DateUtil.isWeekend(DateUtil.parse(date));
        String year = DateUtil.format(DateUtil.parse(date, "yyyy-MM-dd"), "yyyy");
        List<HolidayResponseVo> holidayList = getHoliday(year);
        if (isWeekend) {
            // 查询周末是否上班,补班
            HolidayResponseVo day = holidayList.stream().filter(o -> !o.getIsOffDay())
                    .filter(o -> StrUtil.equals(o.getDate() , date)).findFirst().orElse(null);
            if (ObjectUtil.isNotNull(day)) {
                // 周末调休上班o(╥﹏╥)o
                return false;
            }
            return true;
        }

        // 是否为节假日
        HolidayResponseVo day = holidayList.stream().filter(o -> o.getIsOffDay())
                .filter(o -> StrUtil.equals(o.getDate(), date)).findFirst().orElse(null);
        if (ObjectUtil.isNotNull(day)) {
            return true;
        }
        // 工作日正常上班o(╥﹏╥)o
        return false;
    }
}
